package DB;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Properties;

public class DB {
	private static DB singleton = new DB();
	private HashMap<String, String> parameters = new HashMap<String, String>();
	protected static Connection connection = null;
	
	public static DB getInstance(){
		return singleton;
	}
	
	public Connection connect() {
		Boolean isPrivate = false;
		initParametersPublic();
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection(parameters.get("url"), parameters.get("user"), parameters.get("password"));
		} catch (SQLException | ClassNotFoundException e) {
			isPrivate = true;
		}
		if(isPrivate){
			initParametersPrivate();
			try {
				Class.forName("com.mysql.jdbc.Driver");
				connection = DriverManager.getConnection(parameters.get("url"), parameters.get("user"), parameters.get("password"));
			} catch (SQLException | ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		return connection;
	}
	
	public void disconnect(){
		try {
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	private void initParametersPrivate(){
		Properties props = new Properties();
		InputStream file = DB.class.getResourceAsStream("parameters_database.properties");
		try {
			props.load(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		StringBuffer url = new StringBuffer("jdbc:mysql://");
		url.append(props.getProperty("database.host.private"));
		url.append("/");
		url.append(props.getProperty("database.name"));
		parameters.put("url", url.toString());
		parameters.put("user", props.getProperty("database.user"));
		parameters.put("password", props.getProperty("database.password"));
	}
	
	private void initParametersPublic(){
		Properties props = new Properties();
		InputStream file = DB.class.getResourceAsStream("parameters_database.properties");
		try {
			props.load(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		StringBuffer url = new StringBuffer("jdbc:mysql://");
		url.append(props.getProperty("database.host.public"));
		url.append("/");
		url.append(props.getProperty("database.name"));
		parameters.put("url", url.toString());
		parameters.put("user", props.getProperty("database.user"));
		parameters.put("password", props.getProperty("database.password"));
	}
}
